package com.yserp.api.baseapi;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import cn.basecode.server.common.constants.ConstCode;
import cn.basecode.server.common.constants.ResCode;
import cn.basecode.server.common.log4j.BaseLogger;
import cn.basecode.server.common.propertie.SystemConf;
import cn.basecode.server.common.service.LoggerService;
import cn.basecode.server.common.util.ConvertUtil;
import cn.basecode.server.common.util.StringUtil;
import cn.basecode.server.common.util.ThreadFactory;
import cn.basecode.server.common.vo.BaseUserBean;
import cn.basecode.server.common.vo.OperLogBean;
import cn.basecode.server.common.vo.ResultDO;
import com.xiaoleilu.hutool.db.Session;
import org.jeecgframework.core.interceptors.DateConvertEditor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;



public class erpController {
	public final static String OPEN_ID="openId";
	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		// String类型转换，将所有传递进来的String进行HTML编码，防止XSS攻击
//		binder.registerCustomEditor(String.class, new HtmlEscapeEditor());
		binder.registerCustomEditor(Date.class, new DateConvertEditor());
	}
	
	public boolean isPhoneRequest(){
		HttpServletRequest request=getRequest();
		String device=request.getHeader("DEVICE");
		return "ANDROID".equals(device);
	}
	
	public Map<String,Object> request2Map(HttpServletRequest request){
		
		Map<String,Object> resultMap=new HashMap<String,Object>();
		 Map<String, String[]> tmp=request.getParameterMap();
		for(String key:tmp.keySet()){
			String[] ary=tmp.get(key);
			resultMap.put(key, StringUtil.toStr(ary, ""));
		}
        return resultMap;
	}
	
	/**
	 * 获取项目基础路径.
	 * @param req
	 * @return
	 */
	protected String getBasePath(HttpServletRequest req){
		StringBuffer baseUrl = new StringBuffer();
		String scheme = req.getScheme();
		int port = req.getServerPort();

		baseUrl.append(scheme); // http, https
		baseUrl.append("://");
		baseUrl.append(req.getServerName());
		if ((scheme.equals("http") && port != 80) || (scheme.equals("https") && port != 443))
		{
			baseUrl.append(':');
			baseUrl.append(req.getServerPort());
		}
		return baseUrl.toString();
	}
	/**
	 * 获取用户IP.
	 * @param req
	 * @return
	 */
	protected static String getIp(HttpServletRequest req){
		String ip = req.getHeader("x-forwarded-for");
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = req.getHeader("Proxy-Client-IP");
	    }
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = req.getHeader("WL-Proxy-Client-IP");
	    }
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = req.getRemoteAddr();
	    }
	    ip = ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
	    return ip;
	}
	
	/**
	 * 获取用户操作的设备.
	 * @param req
	 * @return
	 */
	protected static short getLoginDev(HttpServletRequest req){
		String loginDev=req.getHeader("LOGIN_DEV");
		if(loginDev==null){
			loginDev="web";
		}
		String value= ConstCode.getKeyBySV("LOG_LOGIN_DEV", loginDev);
		if(value==null){
			return Short.parseShort(ConstCode.LOGIN_DEV_WEB.getKey());
		}
		return Short.parseShort(value);
	}
	/**
	 * 获取当前用户所述（最高级别）机构名字
	 * @return
	 */
//	protected String getUserDeptName(){
//		return getCurrentLoginUser().getUserDeptName();
//	}
	/**
	 *获取当前用户所述（最高级别）机构Id
	 * @return
	 */
//	protected String getUserDeptId(){
//		return getCurrentLoginUser().getUserDeptId();
//	}
	/**
	 * 获取当前用户最高级别部门信息
	 * @return
	 */
//	protected TSysOrganizationBean getUserDeptInfo(){
//		return getCurrentLoginUser().getUserDeptInfo();
//	}
	/**
	 * 从request中获取IP地址转成int
	 * @param req
	 * @return
	 */
	protected static int getIntIp(HttpServletRequest req){
		String strIp=getIp(req);
		return ConvertUtil.ipToInt(strIp);
	}
	/**
	 * 取得HttpRequest的简化函数.
	 */
	protected HttpServletRequest getRequest(){
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	}
	protected HttpSession getSession(){
		return getRequest().getSession();
	}

	/**
	 *获取当前用户所述（最高级别）机构COde
	 * @return
	 */
//	protected String getUserDeptCode(){
//		return getCurrentLoginUser().getUserDeptCode();
//	}
//	protected HttpSession getSession(boolean isNew){
//		return getRequest().getSession(isNew);
//	}
	/**
	 * 获取当前用户的登录号
	 * @return
	 */
//	protected String getCurrentLoginName(){
//		 return getCurrentLoginUser().getLoginName();
//	}
	/**
	 * 获取当前登录用户数据
	 * @return
	 */
//	protected BSystemUserBean getCurrentLoginUser(){
//		 Session session = SecurityUtils.getSubject().getSession();
//		return  (BSystemUserBean)session.getAttribute("currentUser");
//	}
	/**
	 * 获取当前登录用户部门code
	 * @return
	 */
//	protected String getCurrentLoginUserDeptCode(){
//		return getCurrentLoginUser().getUserDeptCode();
//	}
	/**
	 * 新增人的数据放入Map中
	 * @param params
	 */
	public void createUserMsgAddToMap(Map<String,Object> params){
//		params.put("CREATE_ORGNAME", getUserDeptName());
//		params.put("CREATE_ORGID", getUserDeptId());
//		params.put("CREATE_ORGCODE", getUserDeptCode());
//		params.put("CREATE_ID", getCurrentUserId());
//		params.put("CREATE_NAME", getCurrentUserName());
	}
	/**
	 * 修改人的的数据放入Map中
	 * @param params
	 */
	public void updateUserMsgAddToMap(Map<String,Object> params){
//		params.put("MODIFY_ORGNAME", getUserDeptName());
//		params.put("MODIFY_ORGID", getUserDeptId());
//		params.put("MODIFY_ID", getCurrentUserId());
//		params.put("MODIFY_NAME", getCurrentUserName());
	}
	/**
	 * 获取当前用户的真实姓名
	 * @return
	 */
//	protected String getCurrentUserName(){
//		return getCurrentLoginUser().getUserName();
//	}
	/**
	 * 获取当前用户的userId
	 * @return
	 */
//	protected String getCurrentUserId(){
//		return getCurrentLoginUser().getUserId();
//	}
	/**
	 * 获取用户登录日志Id，（登出时使用）
	 * @return
	 */
//	protected String getCurrentUserLoginLogId(){
//		return getCurrentLoginUser().getLoginLogId();
//	}
	protected String getParameter(String name){
		return getRequest().getParameter(name);
	}
	protected ResultDO<String> toErrorResult(BindingResult br){
		return new ResultDO<String>(ResCode.COM_PARAMERROR.getResCode(),br.getAllErrors().get(0).getDefaultMessage().toString());
	}
	protected ResultDO<String> toErrorResult(String code,String dedsc){
		return new ResultDO<String>(code,dedsc);
	}
	protected String toErrorResultString(BindingResult br){
		ResultDO<String> dojo= toErrorResult(br);
		return ConvertUtil.toJsonString(dojo);
	}
	protected String toErrorResultString(ResultDO<?> dojo){
		return ConvertUtil.toJsonString(dojo);
	}
	protected String toErrorResultString(String code,String dedsc){
		ResultDO<String> dojo= toErrorResult(code,dedsc);
		return ConvertUtil.toJsonString(dojo);
	}
	protected ResultDO<String> toErrorResult(ResCode coded){
		return new ResultDO<String>(coded.getResCode(),coded.getResDescription());
	}
	protected <T>ResultDO<T> toSuccessResult(T br){
		return new ResultDO<T>(br);
	}
	protected <T>ResultDO<T> toSuccessResult(){
		return new ResultDO<T>(true);
	}
	protected <T>ResultDO<T> toErrorResult(ResultDO<T> _sRd){
		return new ResultDO<T>(_sRd.getErrorCode(),_sRd.getErrorMsg(),_sRd.getObj());
	}
	@Autowired
	private LoggerService addLoggerService;
	protected  void insertLogger(HttpServletRequest req,String type,String content,String params){
		try{
			final OperLogBean bean=new OperLogBean();
			bean.setOprUrl(req.getRequestURL().toString());
			bean.setOprParams(params);
			bean.setOprContent(content);  
			bean.setReqParams(ConvertUtil.toJsonString(req.getParameterMap()));
			bean.setOprType(type);
			bean.setSystemId(SystemConf.getInstance().getSystemId());
			bean.setSystemName(SystemConf.getInstance().getSystemName());
//			bean.setUserId(getCurrentUserId());
//			bean.setUserName(getCurrentUserName());
//			bean.setLoginId(getCurrentUserLoginLogId());
//			bean.setLoginName(getCurrentLoginName());
//			bean.setUserOrgId(getCurrentLoginUser().getUserDeptId());
//			bean.setUserOrgName(getCurrentLoginUser().getUserDeptName());
			ThreadFactory.execute(new Runnable() {
				@Override
				public void run() {
					addLoggerService.insertOperLog(bean);
				}
			});
		}catch(Exception e){
			BaseLogger.error("插入日志失败",e,content);
		}
		
	}
	protected  void insertLogger(HttpServletRequest req,String type,String content,String params,BaseUserBean user){
		try{
			final OperLogBean bean=new OperLogBean();
			bean.setOprUrl(req.getRequestURL().toString());
			bean.setOprParams(params);
			bean.setOprContent(content);  
			bean.setReqParams(ConvertUtil.toJsonString(req.getParameterMap()));
			bean.setOprType(type);
			bean.setSystemId(SystemConf.getInstance().getSystemId());
			bean.setSystemName(SystemConf.getInstance().getSystemName());
			bean.setUserId(user.getUserId());
			bean.setUserName(user.getUserName());
			bean.setLoginId(user.getLoginLogId());
			bean.setLoginName(user.getLoginName());
			bean.setUserOrgId(user.getUserDeptId());
			bean.setUserOrgName(user.getUserDeptName());
			ThreadFactory.execute(new Runnable() {
				@Override
				public void run() {
					addLoggerService.insertOperLog(bean);
				}
			});
		}catch(Exception e){
			BaseLogger.error("插入日志失败",e,content);
		}
		
	}
	protected  void insertLogger(String type,String content,String params){
		insertLogger(getRequest(), type, content, params);
	}
	protected  void insertLogger(String type,String content){
		insertLogger(getRequest(), type, content, null);
	}
	protected  void insertLogger(HttpServletRequest req,String type,String content){
		insertLogger(req, type, content, null);
	}
	private final static String[] agent = { "Android", "iPhone", "iPod","iPad", "Windows Phone", "MQQBrowser" };

	public static boolean checkAgentIsMobile(HttpServletRequest request) {
		String ua = request.getHeader("User-Agent");
		boolean flag = false;
		if (ua!=null&&(!ua.contains("Windows NT") || (ua.contains("Windows NT") && ua.contains("compatible; MSIE 9.0;")))) {
			// 排除 苹果桌面系统
			if (!ua.contains("Windows NT") && !ua.contains("Macintosh")) {
				for (String item : agent) {
					if (ua.contains(item)) {
					flag = true;
					break;
					}
				}
			}
		}
		return flag;
	}
	 /**
	   *从cookie中获取openId
	   * @param request 内容类型
	   * @return null
	   */
	  public static String getOpenIdInCookie(HttpServletRequest request) {
		  Cookie[] cookies=request.getCookies();
			String openId=null;
			if(cookies!=null&&cookies.length>0){
				for(Cookie cookie:cookies){
					if(OPEN_ID.equals(cookie.getName())){
						openId=cookie.getValue();
						break;
					}
				}
			}
		return openId;
	  }
	
}
